# 当需要对参数进行限制时，可以将参数定义为私有变量，并且定义 getter 和 setter 函数来对变量进行操作
# 但是这样不如直接调用属性进行获取和赋值来的简单，通过@property属性，就可以既实现对参数的限制，又能直接像调用属性一样进行赋值
class Student(object):
    @property
    def score(self):
        return self.__score
    
    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError("score must be an integer")
        if value < 0 or value > 100:
            raise ValueError("score must between 0~100")
        self.__score = value


s = Student()
s.score = 30
print(s.score)

try:
    s.score = 103423
except ValueError as e:
    print(e)

class Student(object):
    @property
    def birth(self):
        return self._birth

    @birth.setter
    def birth(self, value):
        self._birth = value

    @property
    def age(self):
        return 2015 - self._birth

a = Student()
a.birth = 2001
print(a.birth)

print(a.age)
try:
    a.age = 20
except:
    print("set age failed!")


# experiment
class Screen(object):
    @property
    def width(self):
        return self._width
    @width.setter
    def width(self, val):
        self._width = val

    @property
    def height(self):
        return self._height
    
    @height.setter
    def height(self, val):
        self._height = val

    @property
    def resolution(self):
        return self._width * self._height

# 测试:
s = Screen()
s.width = 1024
s.height = 768
print('resolution =', s.resolution)
if s.resolution == 786432:
    print('测试通过!')
else:
    print('测试失败!')

try:
    s.resolution = 100
except:
    print("resolution is only readable!")
